package com.emm.yixun.mobile.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.ToExamineAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetAuditList;
import com.emm.yixun.mobile.model.GetAuditList.AuditList;
import com.emm.yixun.mobile.ui.from.FromDetailsActivity;
import com.emm.yixun.mobile.ui.signed.SigneDetailsdActivity;
import com.emm.yixun.mobile.ui.subscribe.SubscriDetailsActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.swu.pulltorefresh.PullToRefreshSwipeMenuListView;
import cn.swu.pulltorefresh.PullToRefreshSwipeMenuListView.IXListViewListener;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * 
 * <p>
 * <b>Title：</b> 审核列表
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月6日 下午4:06:36
 */
public class ToExamineActivity extends SwipeBackActivity implements IXListViewListener {

	private static final String TAG = "ToExamineActivity";

	/** 标题 */
	TextView title_main;

	/** 返回按钮 */
	ImageView back_btn;

	/** 审核申请列表 */
	PullToRefreshSwipeMenuListView listView_notice;

	/** 查询审核列表 */
	GetAuditList date;

	/** 适配器 */
	ToExamineAdapter adapter;

	/** 审核列表 */
	ArrayList<AuditList> auditList;

	/** 侧滑关闭框架 */
	private SwipeBackLayout mSwipeBackLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.to_examine_activity);

		// 侧滑关闭框架配置方法
		SetSwipeBackLayout(mSwipeBackLayout);

		BaseActivity.activity = this;
		initView();

		SetRelativiLayoutPadding(R.id.main_head_top_rela);

		initBtn();

		// 查询审核列表接口
		getAuditList("" + pageNumber, "" + pageSize, 1);
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化view
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午5:18:55
	 */
	private void initView() {
		title_main = (TextView) findViewById(R.id.title_main);
		back_btn = (ImageView) findViewById(R.id.back_btn);
		title_main.setText(getString(R.string.to_examine_title));
		listView_notice = (PullToRefreshSwipeMenuListView) findViewById(R.id.listView_to_examine);

		// 设置列表参数：是否可刷新、可加载更多..
		listView_notice.setPullRefreshEnable(true);
		listView_notice.setPullLoadEnable(true);
		listView_notice.setXListViewListener(this);
		listView_notice.setRefreshTime(EmmApplication.getData("RefreshTime_to_examine"));
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化监听事件
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午5:19:03
	 */
	private void initBtn() {
		back_btn.setVisibility(View.VISIBLE);
		back_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		listView_notice.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Log.v(TAG, "position:" + position);
				if (position == 0) {
					Log.v(TAG, "点击头部，不做跳转处理");
				} else {

					if (EmmApplication.IsLoadingFromList) {
						Log.v(TAG, "正在加载新界面，该次点击无效");
						return;
					}
					EmmApplication.IsLoadingFromList = true;

					position--;
					Intent intent = new Intent();
					intent.putExtra("taskId", getaud.getAuditList().get(position).getTaskId());
					if ("认筹".equals(getaud.getAuditList().get(position).getAuditType())) {
						intent.setClass(ToExamineActivity.this, FromDetailsActivity.class);
						intent.putExtra("IsToExamine", "1");
						intent.putExtra("payDepositId", getaud.getAuditList().get(position).getBusinessId());
					} else if ("认购".equals(getaud.getAuditList().get(position).getAuditType())) {
						intent.setClass(ToExamineActivity.this, SubscriDetailsActivity.class);
						intent.putExtra("subscribeId", getaud.getAuditList().get(position).getBusinessId());
						intent.putExtra("IsToExamine", "1");
					} else if ("签约".equals(getaud.getAuditList().get(position).getAuditType())) {
						intent.setClass(ToExamineActivity.this, SigneDetailsdActivity.class);
						intent.putExtra("signId", getaud.getAuditList().get(position).getBusinessId());
						intent.putExtra("IsToExamine", "1");
					}
					startActivity(intent);
				}
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		BaseActivity.activity = this;
		if (EmmApplication.IsReloadToExamine) {
			Log.v(TAG, "刷新界面");
			EmmApplication.IsReloadToExamine = false;
			h.sendEmptyMessage(1);
		}

	}

	/** 刷新 */
	@Override
	public void onRefresh() {
		listView_notice.stopLoadMore();
		h.sendEmptyMessage(1);
		label = 1;
	}

	/** 加载更多 */
	@Override
	public void onLoadMore() {
		listView_notice.stopRefresh();
		h.sendEmptyMessage(2);
	}

	/** 模拟加载效果 */
	Handler h = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {
				pageNumber = 1;
				Log.v(TAG, "pageSize>" + pageNumber + ">=<pageSize>" + pageSize);
				getAuditList("" + 1, "" + 10, 1);
			} else if (msg.what == 2) {
				if (label == 2) {
					getAuditList("" + 1, "" + pageSize, 2);
					Log.e(TAG, "=======");
					listView_notice.stopLoadMore();
				} else {
					pageNumber++;
					pageSize = pageNumber * 10;
					getAuditList("" + 1, "" + pageSize, 2);
					Log.e(TAG, "-----------");
				}
			}
		};
	};

	/** 审核列表数据源 */
	GetAuditList getaud;

	/** 页码 */
	int pageNumber = 1;

	/** 页码条数 */
	int pageSize = 10;

	int label = 1;

	boolean IsLoading = true;

	/**
	 * <p>
	 * <b>Title：</b> 查询审核列表接口
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param pageNumbers
	 * @param pageSizes
	 * @param opentype
	 * @author tangxin
	 * @date 2016年12月21日 下午4:11:24
	 */
	private void getAuditList(String pageNumbers, final String pageSizes, final int opentype) {
		EmmApplication.updateUrl("getAuditList");
		Map<String, String> map = new HashMap<String, String>();
		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("projectCode", EmmApplication.getProjectCode());
		map.put("pageSize", pageSizes);
		map.put("pageNumber", pageNumbers);
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v("getAuditList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
				listView_notice.stopRefresh();
				String timed = EmmApplication.dataTime(EmmApplication.geTime(), "yyyy-MM-dd HH:mm");
				listView_notice.setRefreshTime(timed);
				listView_notice.stopLoadMore();
				EmmApplication.setData("RefreshTime_to_examine", timed);
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
				listView_notice.stopRefresh();
				String timed = EmmApplication.dataTime(EmmApplication.geTime(), "yyyy-MM-dd HH:mm");
				listView_notice.setRefreshTime(timed);
				listView_notice.stopLoadMore();
				EmmApplication.setData("RefreshTime_to_examine", timed);
			}

			@Override
			public void onStart() {
				super.onStart();
				if (opentype == 1) {
					Loading.showDialogForLoading(ToExamineActivity.this, "正在加载...", false, true, 60000);
				}
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v(TAG, "content:" + content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				GetAuditList getaudfs = JSONObject.parseObject(resData.toString(), GetAuditList.class);

				if ("1".equals(getaudfs.getResult())) {
					Log.v("获取成功", "getaud");
					if (getaudfs.getAuditList() != null) {
						if (opentype == 1) {// 刷新
							getaud = new GetAuditList();
							getaud = getaudfs;
						} else {// 加载
							if (getaud != null) {
								// getaud.getAuditList().addAll(getaudfs.getAuditList());
								getaud = getaudfs;
							} else {
								getaud = new GetAuditList();
								// getaud.getAuditList().addAll(getaudfs.getAuditList());
								getaud = getaudfs;
							}
							Log.e("=======", "getaudfs.getAuditList().size():" + getaudfs.getAuditList().size()
									+ "    Integer.parseInt(pageSizes):" + Integer.parseInt(pageSizes));
							if (getaudfs.getAuditList().size() < Integer.parseInt(pageSizes)) {// 说明没有加载更多了
								label = 2;
							}
						}
						Log.v(TAG, "getaud=>" + getaud.getAuditList().size());
						if (adapter == null) {
							adapter = new ToExamineAdapter(ToExamineActivity.this, getaud);
							listView_notice.setAdapter(adapter);
						} else {
							adapter.SetDateNotify(getaud);
						}
					} else {
						// 停止加载刷新动画
						listView_notice.stopLoadMore();
						listView_notice.stopRefresh();
						if (opentype == 2) {
							label = 2;
						} else {
							if (getaud != null && getaud.getAuditList() != null) {
								getaud.getAuditList().clear();
							} else {
								getaud = new GetAuditList();
							}
							if (adapter == null) {
								adapter = new ToExamineAdapter(ToExamineActivity.this, getaud);
								listView_notice.setAdapter(adapter);
							} else {
								adapter.SetDateNotify(getaud);
							}
							if (opentype == 1) {
							} else
								EmmApplication.T("没有查询到数据");
						}
					}
				} else {
					EmmApplication.T(getaudfs.getErrorMsg().toString());
					Log.v("获取失败", "errorCode:" + getaudfs.getErrorCode().toString() + "errorMsg:"
							+ getaudfs.getErrorMsg().toString());
				}
			}
		});
	}

}
